'''
@create_time: 2025/10/24
@Author: GeChao
@File: notification_manager.py
@Description: 统一管理测试报告通知
'''

import configparser
from pathlib import Path
from tools.log import Logger

logger = Logger().logger


class NotificationConfig:
    """通知配置管理类"""
    
    def __init__(self, config_file='conf/notification.ini'):
        self.config_path = Path(__file__).parent.parent / config_file
        self.config = configparser.ConfigParser()
        
        if not self.config_path.exists():
            logger.warning(f"配置文件不存在: {self.config_path}")
            self._create_default_config()
        
        self.config.read(self.config_path, encoding='utf-8')
    
    def _create_default_config(self):
        """创建默认配置文件"""
        self.config_path.parent.mkdir(parents=True, exist_ok=True)
        with open(self.config_path, 'w', encoding='utf-8') as f:
            f.write("""[DingTalk]
enabled = no
webhook = 
secret = 

[Email]
enabled = no
recipients = 

[Report]
report_url = http://127.0.0.1:38495
""")
    
    @property
    def dingtalk_enabled(self):
        """钉钉通知是否启用"""
        return self.config.get('DingTalk', 'enabled', fallback='no').lower() == 'yes'
    
    @property
    def dingtalk_webhook(self):
        """钉钉Webhook地址"""
        return self.config.get('DingTalk', 'webhook', fallback='')
    
    @property
    def dingtalk_secret(self):
        """钉钉加签密钥"""
        return self.config.get('DingTalk', 'secret', fallback='')
    
    @property
    def email_enabled(self):
        """邮件通知是否启用"""
        return self.config.get('Email', 'enabled', fallback='no').lower() == 'yes'
    
    @property
    def email_recipients(self):
        """邮件收件人列表"""
        recipients = self.config.get('Email', 'recipients', fallback='')
        return [r.strip() for r in recipients.split(',') if r.strip()]
    
    @property
    def report_url(self):
        """报告服务器地址"""
        return self.config.get('Report', 'report_url', fallback='http://127.0.0.1:38495')


class NotificationManager:
    """通知管理器"""
    
    def __init__(self, config_file='conf/notification.ini'):
        self.config = NotificationConfig(config_file)
    
    def send_notifications(self):
        """发送所有启用的通知"""
        from pathlib import Path
        import subprocess
        
        script_path = Path(__file__).parent.parent / 'generate_test_report.py'
        
        # 发送钉钉通知
        if self.config.dingtalk_enabled:
            if self.config.dingtalk_webhook:
                logger.info("📱 发送钉钉通知...")
                cmd = f'python "{script_path}" -dt 1 -dtw "{self.config.dingtalk_webhook}"'
                if self.config.dingtalk_secret:
                    cmd += f' -dts "{self.config.dingtalk_secret}"'
                subprocess.Popen(cmd, shell=True)
            else:
                logger.warning("⚠️  钉钉通知已启用但未配置Webhook地址")
        
        # 发送邮件通知
        if self.config.email_enabled:
            if self.config.email_recipients:
                logger.info("📧 发送邮件通知...")
                for recipient in self.config.email_recipients:
                    cmd = f'python "{script_path}" -em 1 -emt "{recipient}"'
                    subprocess.Popen(cmd, shell=True)
            else:
                logger.warning("⚠️  邮件通知已启用但未配置收件人")


if __name__ == '__main__':
    # 测试配置读取
    config = NotificationConfig()
    print(f"钉钉通知: {config.dingtalk_enabled}")
    print(f"钉钉Webhook: {config.dingtalk_webhook}")
    print(f"邮件通知: {config.email_enabled}")
    print(f"邮件收件人: {config.email_recipients}")
    print(f"报告地址: {config.report_url}")
